<template>
  <view>
    <!-- 搜索盒子 -->
    <view class = "search-box">
      <uni-search-bar  focus="true" placeholder="请输入搜索内容"  cancelButton="none" :radius="50"  @input="input" >
      </uni-search-bar>
      <view class="seaBtn"><image v-on:touchstart = "serTouchstart"  v-on:touchend = "serTouchend" :src="seaSrc" ></image></view>
    </view>
    
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" @click="gotoGoodsDetial(item)" v-for = '(item,i) in searchResults' :key = "i">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size="18"></uni-icons>
      </view>
      
    </view>
    
    <!-- 搜索历史 -->
    <view class="history-box" v-if="historyList.length !== 0 && searchResults.length === 0"  >
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons @click = "deleteHistory" type="trash" size="17"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag :text="item" v-for="(item, i) in historys" @click="gotoGoodsList(item)" :key="i"></uni-tag>
      </view>
    </view>
    
  </view>
</template>

<script>
  export default {
    onLoad() {
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    computed:{
        historys() {
          // 注意：由于数组是引用类型，所以不要直接基于原数组调用 reverse 方法，以免修改原数组中元素的顺序
          // 而是应该新建一个内存无关的数组，再进行 reverse 反转
          return [...this.historyList].reverse()
        }
    },
    data() {
      return {
        seaSrc:"/static/sea1.png",
        //延时器
        timer:null,
        //搜索关键字
        kw:'',
        searchResults: [] ,   //搜索结果列表
        historyList: ['苹果','车子','男衬衫']
      }
    },
    methods: {
      input(e){
        //清楚计数器
        clearTimeout(this.timer)
       // 设置计时器,500毫秒
        this.timer = setTimeout(()=>{
          this.kw = e
          // console.log(this.kw)
          this.getSearchList()
        },500)
      },
        async getSearchList() {
          // 判断关键词是否为空
          if (this.kw === '') {
            this.searchResults = []
            return
          }
          // 发起请求，获取搜索建议列表
          const { data: res } = await uni.$http.get('https://api-hmugo-web.itheima.net/api/public/v1/goods/qsearch', { query: this.kw })
          if (res.meta.status !== 200) return uni.$showMsg()
          this.searchResults = res.message;
          console.log(this.searchResults);
          this.saveSearchHistory();
        },
         serTouchstart(){
           this.seaSrc ="/static/sea2.png"
         },
         serTouchend(){
           this.seaSrc ="/static/sea1.png"
           if(this.kw === '') return
           this.gotoGoodsList(this.kw)
         },
         saveSearchHistory(){
           this.historyList.push(this.kw);
           
             // 1. 将 Array 数组转化为 Set 对象
             const set = new Set(this.historyList)
             // 2. 调用 Set 对象的 delete 方法，移除对应的元素
             set.delete(this.kw)
             // 3. 调用 Set 对象的 add 方法，向 Set 中添加元素
             set.add(this.kw)
             // 4. 将 Set 对象转化为 Array 数组
             this.historyList = Array.from(set)
           
              // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
              uni.setStorageSync('kw', JSON.stringify(this.historyList))
         },
         deleteHistory(){
           this.historyList.splice(0,this.historyList.length)
           uni.setStorageSync('kw', JSON.stringify(this.historyList))
         },
         gotoGoodsList(kw){
           console.log(kw)
            uni.navigateTo({
              url: '/subpkg/goods_list/goods_list?query=' + kw
            })
         },
         gotoGoodsDetial(e){
           uni.navigateTo({
             url:'/subpkg/goods_detail/goods_detail?goods_id='+e.goods_id
           })
         },
      value(){
        console.log("enter")
      }
    }
  }
</script>

<style lang="scss">
.history-box {
  padding: 0 5px;

  .history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40px;
    font-size: 13px;
    border-bottom: 1px solid #efefef;
  }

  .history-list {
    display: flex;
    flex-wrap: wrap;

    .uni-tag {
      margin-top: 5px;
      margin-right: 5px;
    }
  }
}
   .search-box{
     display: flex;
     position: sticky;
     top: 0;
     z-index: 999;
     uni-search-bar{
       flex: 8;
     }
     .seaBtn{
      image{
        height: 50rpx;
        width: 50rpx;
      }
       display: flex;
       flex: 1;
       // padding-bottom: 15rpx;
       padding-right: 15rpx;
       justify-content: center;
       align-items: center;
       font-size: 18;
       background-color: #c00000;
       border-radius: 0rpx;
       // border: 10rpx solid #c00000;
       
     }
   }
   .sugg-list {
  padding: 0 5px;

  .sugg-item {
    font-size: 12px;
    padding: 13px 0;
    border-bottom: 1px solid #efefef;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .goods-name {
      // 文字不允许换行（单行文本）
      white-space: nowrap;
      // 溢出部分隐藏
      overflow: hidden;
      // 文本溢出后，使用 ... 代替
      text-overflow: ellipsis;
      margin-right: 3px;
    }
    
  }

}
</style>
